import axios from 'axios'
import store from '@/store'
import {
  MessageBox,
  Loading
} from 'element-ui'

// 错误提示调用方法
const errorMsgArray = []
const alertError = function(message, callback) {
  if (errorMsgArray.indexOf(message) === -1) {
    const index = errorMsgArray.push(message)
    MessageBox.alert(message, '提示', {
      type: 'error',
      confirmButtonText: '确定',
      callback: () => {
        errorMsgArray.splice(index, 1)
        if (callback) {
          callback()
        }
      }
    })
  }
}
let loading

/* 创建新的axios */
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // 当跨域请求时发送cookie
  timeout: 10000 // 请求时间
})
request.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

request.interceptors.request.use(
  config => {
    // 发送请求
    if (config.url.indexOf('.json') !== -1) {
      config.baseURL = process.env.VUE_APP_BASE_API_JSON
    }

    const token = store.getters.token
    if (token) {
      config.headers['portal-token'] = token
    }

    if (config.isLoading !== false) {
      // 如果配置了isLoading: false，则不显示loading
      // beginLoading()
    }

    loading = Loading.service({
      lock: false,
      text: '加载中...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    return config
  },
  err => {
    alertError('您当前网络不可用，请检查网络设置')
    loading.close()
    return Promise.resolve(err)
  }
)

request.interceptors.response.use(
  response => {
    // 返回数据
    const newToken = response.headers['portal-token'] // 自身用户体系的token
    if (newToken) {
      store.commit('SET_TOKEN', newToken)
    }
    if (response.data.result === 'error') {
      alertError(response.data.message, function() {
        if (response.data.message === '您未登录或者长时间未操作，请重新登录后再操作') {
          store.commit('REMOVE_TOKEN')
          window.location = '/'
        }
      })
    }
    loading.close()
    return response.data
  },
  err => {
    if (!(err && err.response && err.response.data && err.response.data.message)) {
      err.response = {
        data: {
          result: 'error',
          message: '您当前网络不可用，请检查网络设置'
        }
      }
    }
    alertError('您当前网络不可用，请检查网络设置')
    loading.close()
    return Promise.resolve(err.response.data)
  }
)

export {
  request
}
